package com.itheima.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.es.entity.Result;
import com.itheima.es.mapper.SkuMapper;
import com.itheima.es.pojo.GoodInfo;
import com.itheima.es.pojo.Sku;

import com.itheima.es.service.SkuService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    private RestHighLevelClient client;
    //分页查询
    @Override
    public List<Sku> search(int currentPage, int pageSize) {
        Page<Sku> page = page(new Page<>(currentPage,pageSize));
        List<Sku> rowsList = page.getRecords();
        return rowsList;
    }

    public Result queryByQueryString(){
        //连接
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.200.150",9200,"http"))
        );
        //1. 创建searchRequest指定索引库名称
        SearchRequest searchRequest = new SearchRequest("goodInfo");

        //2. 创建SearchSourceBuilder封装查询条件，在商品标题上检索(模糊查询)
        SearchSourceBuilder builder = new SearchSourceBuilder();
        FuzzyQueryBuilder queryBuilder = QueryBuilders.fuzzyQuery("title", "学习Java的书籍");
        queryBuilder.fuzziness(Fuzziness.TWO);
        SearchResponse response = query(queryBuilder);

        //3. 如果参数中有价格price参数，则设置range区间过滤
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");
        rangeQuery.gte(1000);
        rangeQuery.lte(5000);
        query(rangeQuery);


        //10. 封装结果并返回Result（code\msg\data）
        return new Result(response);
    }


    public SearchResponse   query(QueryBuilder queryBuilder){
        SearchResponse searchResponse = null;
        try {
            //1.创建SearchSourceBuilder对象
            SearchSourceBuilder builder = new SearchSourceBuilder();
            //1.1.添加查询条件QueryBuilders(排序，分页等)

            //添加排序查询
            builder.sort("create_time", SortOrder.DESC);//降序
            builder.sort("id",SortOrder.DESC);//降序

            //分页查询
            int page = 1;
            int size = 10;
            int from = (page-1)*size;
            builder.from(from);
            builder.size(size);

            //设置高亮三要素
            HighlightBuilder highlight = SearchSourceBuilder.highlight();
            //高亮显示的域
            HighlightBuilder note = highlight.field("title");
            //高亮显示的前缀<font color='pink'></font>
            highlight.preTags("<font color='pink'>");
            //高亮显示的后缀
            highlight.postTags("</font>");
            builder.highlighter(highlight);

            builder.query(queryBuilder);
            //2.创建SearchRequest对象，并制定索引库名称
            SearchRequest request = new SearchRequest("goodInfo");
            //3.添加SearchSourceBuilder对象到SearchRequest对象source中
            request.source(builder);
            //4.发起请求，得到结果
             searchResponse = client.search(request, RequestOptions.DEFAULT);
            //5.解析结果SearchResponse
            SearchHits hits = searchResponse.getHits();
            //5.1获取总条数
            long totalHits = hits.getTotalHits().value;
            System.out.println("总条数是："+totalHits);
            //5.2获取SearchHits数组，并遍历
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit hit : searchHits) {
                //5.2.1获取其中的_source，是JSON数据
                String jsonString = hit.getSourceAsString();
                //5.2.2把——source反序列化为User对象
                GoodInfo goodInfo = JSON.parseObject(jsonString, GoodInfo.class);


                //解析高亮数据
                HighlightField highlightField = hit.getHighlightFields().get("title"); // get("高亮显示域名称")
                Text[] fragments = highlightField.getFragments();
                String title = StringUtils.join(fragments);//将数组以某种拼接符拼接成新的字符串
                // 判断如果是可以获取到数据则更新到用户对象中
                if (StringUtils.isNotBlank(title)) {
                    goodInfo.setTitle(title);
                }
                System.out.println("title = " + goodInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return searchResponse;
    }




    public List<Sku> findPage(int cuurrentPage,int pageSze){
        Page<Sku> page = page(new Page<>(cuurrentPage, pageSze));
        List<Sku> records = page.getRecords();
        return records;
    }
}
